<template>
	<view class="container-add">
		<navbar :config="config"></navbar>
		<!-- <view class="tabs">
      <view class="tab" :class="{'activeTab': currentTab == index}" v-for="(item, index) in tabList" :key="item.value"
        @click="changeTab(index)">
        {{item.label}}
      </view>
    </view> -->
		<u-form :model="form" ref="formRef" :rules="rulesForm" label-position="top">
			<u-form-item label="银行卡号" prop="pan" class="card-box">
				<view class="bank_name">
					<image class="bank-logo" v-if="bank_logo" :src="bank_logo" mode="widthFix"></image>
					<text class="txt">{{bankForm.local_bank_name}}</text>
				</view>
				<u-input v-model="form.pan" type="number" :clearable="false" placeholder="请输入银行卡号" @blur="blurCard"
					@input="changeCard" />
			</u-form-item>
			<u-form-item label="银行预留手机号" prop="phone">
				<u-input v-model="form.phone" type="number" min="11" maxlength="11" :clearable="false"
					placeholder="请输入银行预留手机号" />
			</u-form-item>
			<u-form-item label="姓名" prop="realName">
				<u-input v-model="form.realName" />
			</u-form-item>
			<u-form-item label="身份证号" prop="certNo">
				<u-input v-model="form.certNo" />
			</u-form-item>
			<!-- <template v-if="currentTab == 0">
        <u-form-item label="协议号" prop="protocol_no">
          <u-input v-model="form.protocol_no" :clearable="false" placeholder="请输入协议号，招行卡必填，其他卡非必填" />
        </u-form-item>
      </template> -->
			<template v-if="cardType == '0001'">
				<u-form-item label="验证码（信用卡背面签名条末三位）" prop="vip_code">
					<u-input v-model="form.vip_code" :clearable="false" placeholder="请输入验证码" />
				</u-form-item>
				<u-form-item label="有效期" prop="expiration">
					<u-input v-model="form.expiration" :clearable="false" placeholder="请输入有效期" />
					<!-- <uni-datetime-picker type="date" :clear-icon="false" v-model="form.expiration" @maskClick="maskClick" /> -->
				</u-form-item>
			</template>
		</u-form>
		<view class="footer">
			<view class="btn" @click="submit">提交</view>
		</view>
		<u-modal v-model="showPayModel" ref="payModel" title="为了您的资金交易安全" :async-close="true" z-index="900"
			:show-cancel-button="true" @confirm="payConfirm" @cancel="payCancel">
			<view class="slot-content">
				<view class="paybody">
					<view class="header-text">
						<text>已经向您的银行卡预留手机号 {{form.phone}} 发送验证码，请注意查收</text>
					</view>
					<view class="sms">
						<u-input v-model="sms_code" type="number" maxlength="6" :clearable="false"
							placeholder="请输入预留手机号验证码" />
						<view class="retry-gary" :class="{'retry': codeCount > 0}" @click="retrySms()"><text
								v-if="codeCount > 0">{{codeCount}}S后</text>重发</view>
					</view>
					<!-- <u-message-input mode="bottomLine" :maxlength="6"></u-message-input> -->
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	let timer
	export default {
		data() {
			return {
				config: {
					back: true,
					title: '新增银行卡',
					color: '#fff',
					backgroundColor: [1, "#FF721B"],
					statusBarFontColor: '#1A1A1A',
				},
				tabList: [{
						label: '借记卡',
						value: 0
					},
					{
						label: '信用卡',
						value: 1
					}
				],
				currentTab: 0,
				form: {},
				bank_logo: '',
				bankForm: {},
				rulesForm: {
					pan: [{
						required: true,
						message: '请输入银行卡号',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					realName: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur'],
					}],
					certNo: [{
						required: true,
						message: '请输入身份证号',
						trigger: ['blur'],
					}],
					phone: [{
						required: true,
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['blur'],
					}, {
						required: true,
						min: 11,
						max: 11,
						message: '手机号必须是11位',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					// protocol_no: [{
					//   required: true,
					//   message: '请输入protocol_no',
					//   // 可以单个或者同时写两个触发验证方式 
					//   trigger: ['change', 'blur'],
					// }],
					vip_code: [{
						required: true,
						message: '请输入验证码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}],
					expiration: [{
						required: true,
						max: 4,
						message: '请输入有效期',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['blur'],
					}]
				},
				cardType: '',
				amount: null,
				orderId: '',
				showPayModel: false, // 验证码弹框
				codeCount: 60, // 银行卡支付短信验证码重发倒计时
				sms_code: '', // 银行卡支付短信验证码
			}
		},
		onReady() {
			this.$refs.formRef.setRules(this.rulesForm);
		},
		onLoad(options) {
			if (options.amount) {
				this.amount = options.amount
			}
			if (options.orderId) {
				this.orderId = options.orderId
			}
		},
		methods: {
			changeTab(i) {
				if (this.currentTab == i) {
					return false;
				}
				this.currentTab = i
				this.form = {}
				this.bankForm = {}
				this.bank_logo = ''
			},
			maskClick() {},
			blurCard(e) {
				if (e) {
					console.log(e);
					this.$http.post('/pay/order/getBankCardInfo', {
						pan: e
					}).then(res => {
						if (res.code == 200) {
							this.cardType = res.data.cardType
						}
					})
					// this.$http.post('/usercard/check', {
					// 	card_id: e
					// }).then(res => {
					// 	if (res.code == 200 && res.data) {
					// 		this.bankForm.local_bank_name = res.data.bank_name
					// 		this.bankForm.local_bank_mark = res.data.bank_mark
					// 		this.bankForm.local_bank_card_type = res.data.bank_card_type
					// 		this.bankForm.local_bank_card_type_name = res.data.bank_card_type_name
					// 		this.bank_logo = this.$mConfig.bankLink + res.data.bank_mark
					// 		if (this.currentTab == 0) {
					// 			if (res.data.bank_card_type != 'DC') {
					// 				this.$mUtil.toast("此卡号不是借记卡号，请输入对应借记卡卡号")
					// 			}
					// 			// if (res.data.bank_mark == 'CMB') {
					// 			//   this.rulesForm.protocol_no = {
					// 			//     required: true,
					// 			//     message: '请输入协议号',
					// 			//     trigger: 'blur',
					// 			//   }
					// 			// }
					// 		} else if (this.currentTab == 1) {
					// 			if (res.data.bank_card_type != 'CC') {
					// 				this.$mUtil.toast("此卡号不是信用卡号，请输入对应信用卡卡号")
					// 			}
					// 		}
					// 	}
					// })
				} else {
					this.bankForm = {}
					this.bank_logo = ''
				}
			},
			changeCard(e) {
				if (!e) {
					this.bankForm = {}
					this.bank_logo = ''
				}
			},
			// next() {
			//   this.$refs.formRef.validate(valid => {
			//     if (valid) {
			//       console.log('验证通过');
			//       if (this.currentTab == 0) {
			//         this.form.credit = false
			//         this.form.protocol_no = '34463343'
			//       } else {
			//         this.form.credit = true
			//       }
			//       this.$http.post('/usercard/save', {
			//         ...this.form,
			//         ...this.bankForm
			//       }).then(res => {
			//         if (res.code == 200) {
			//           setTimeout(() => {
			//             uni.redirectTo({
			//               url: `/pages/order/banks/mobileCode?type=add&id=${res.data.id}`
			//             })
			//           }, 500)
			//         }
			//       })
			//     } else {
			//       console.log('验证失败');
			//     }
			//   });
			// },
			submit() {
				const personal = uni.getStorageSync('personal')
				this.$refs.formRef.validate(valid => {
					if (valid) {
						console.log('验证通过');
						if (!
							/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
							.test(this.form.certNo)) {
							this.$mUtil.toast('请检查身份证号')
							return false
						}
						this.form.amount = this.amount;
						this.form.userId = personal.mobile;
						this.form.userName = personal.real_name;
						this.form.payOrderId = this.orderId;
						// 首次绑定银行卡
						this.getFirstBindingCard(this.form)
					} else {
						console.log('验证失败');
					}
				});

			},
			// 首次添加
			getFirstBindingCard(data) {
				console.log(data)
				this.$http.post('/pay/order/firstBindingCard', data).then(res => {
					// console.log(res)
					if (res.code == 200) {
						this.showPayModel = true;
						timer = setInterval(() => {
							this.codeCount--
							if (this.codeCount == 0) {
								clearInterval(timer)
							}
						}, 5000)
					}
				})
			},
			payConfirm() {
				// this.$refs.payModel.clearLoading()
				if (!this.sms_code) {
					return this.$mUtil.toast('短信验证码不能为空');
				}
				if (this.sms_code.length != 6) {
					return this.$mUtil.toast('短信验证码不正确');
				}
				uni.showLoading({
					title: '支付中...',
					mask: true
				})
				this.$http.post('/pay/order/pay', {
					pay_order_id: this.orderId,
					pay_mode: 20,
					valid_code: this.sms_code
				}).then(res => {
					if (res.code == 200) {
						this.$mUtil.toast("支付成功")
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/order/orderList/orderList?keys=-1'
							})
						}, 1000)
					} else {
						uni.hideLoading()
					}
				}).catch(err => {
					uni.hideLoading()
					this.loading = false;
					this.showPayModel = false;
					this.$mUtil.toast(res.msg)
				})
			},
			payCancel() {
				this.$mUtil.toast('已取消支付');
				this.showPayModel = false;
			},
			// 重发
			retrySms() {
				if (this.codeCount > 0) return this.$mUtil.toast('请稍后重试');
				this.codeCount = 60
				uni.showLoading({
					title: '重发中...',
					mask: true
				})
				this.getFirstBindingCard(this.form)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container-add {
		padding-bottom: 200rpx;
	}

	.tabs {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 40rpx 100rpx;
		border: 1rpx solid #1684FC;
		color: #1684FC;
		border-radius: 10rpx;

		.tab {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 50%;
			height: 60rpx;
		}

		.activeTab {
			color: #fff;
			background-color: #1684fc;
		}
	}

	.u-form {
		padding: 0 30rpx;

		.card-box {

			/deep/ .u-form-item--right__content__slot {
				display: flex;
				flex-direction: column;
				align-items: flex-start;

				.u-input {
					width: 100%;
				}
			}
		}

		.bank_name {
			display: flex;
			align-items: center;

			.txt {
				font-size: 30rpx;
				font-weight: bold;
			}
		}

		.bank-logo {
			width: 250rpx;
		}
	}

	.footer {
		width: 100%;
		padding: 30rpx 60rpx;
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		z-index: 9;

		.btn {
			width: 100%;
			color: #fff;
			text-align: center;
			line-height: 85rpx;
			border: 1rpx solid #FF721B;
			border-radius: 44rpx;
			background-color: #FF721B;
			font-size: 28rpx;
			font-family: PingFang SC, PingFang SC-Regular;
			font-weight: 400;
			text-align: center;
		}
	}

	.paybody {
		padding: 20rpx 30rpx;

		/deep/ .u-input {
			border-bottom: 2rpx solid #dcdfe6;
		}

		.header-text {
			margin-bottom: 20rpx;
		}

		.sms {
			display: flex;
			align-items: center;

			.retry-gary {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 180rpx;
				margin-left: 40rpx;
				padding: 20rpx 10rpx;
				background-color: #FF721B;
				border-radius: 10rpx;
				color: #fff;
			}

			.retry {
				background-color: gray;
			}
		}
	}
</style>